package com.itheima.controller;

import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * @author benben278
 * @create 2022-03-18 9:58
 */
//处理会员相关操作的
@RestController
@RequestMapping("/member")
public class MemberController {
    @Autowired
    private RedisTemplate redisTemplate;
//    private JedisPool jedisPool;
    @Autowired
    private MemberService memberService;
    //手机号快速登录
    @RequestMapping("/login.do")
    public Result login(HttpServletResponse response, @RequestBody Map map){
        //取出手机号
        String telephone = (String) map.get("telephone");
        //获取页面提交的验证码
        String validateCode = (String) map.get("validateCode");
        //从redis中获取保存的验证码
//        String validateCodeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        String validateCodeInRedis = redisTemplate.opsForValue().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN).toString();
        if (validateCodeInRedis!=null&&validateCode!=null&&validateCode.equals(validateCodeInRedis)){
            //验证码输入正确
            //判断当前用户是否是会员（查询会员表来确定）
            Member member = memberService.findByTelephone(telephone);
            if(member==null){
                //不是会员，自动完成注册（自动将当前用户信息保存到会员表）
               // member = new Member();  //这里是否需要new，考虑一下
                member.setRegTime(new Date());
                member.setPhoneNumber(telephone);
                memberService.add(member);
            }
            //登录成功
            //向客户端浏览器写入Cookie，内容为手机号，跟踪用户
            Cookie cookie=new Cookie("login_member_telephone",telephone);
            cookie.setPath("/");//路径
            cookie.setMaxAge(60*60*24*30);//有效期30天
            response.addCookie(cookie);
            //保存会员信息到Redis中
            String json = JSON.toJSON(member).toString();//redis里面不能直接保存java对象，需要序列化成json串
            //jedisPool.getResource().setex(telephone,60*30,json);//key:telephone   时间：60秒*30 value:json
            redisTemplate.opsForValue().set(telephone,json,60*30);
            return new Result(true,MessageConstant.LOGIN_SUCCESS);
        }else {
            //验证码输入错误
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }
}
